<template>
  <div class="v-add-property g-jc-sb">
    <div class="g-flex-1 _list_scroll">
      <div
        v-for="(item, index) of valueData"
        :key="index"
        :class="{ _selected: selected && selectedModelId === item.id }"
        class="g-pd-l-8 g-one-line"
        @click="handleClickItem(item)"
        @contextmenu="propertyModelContextMenu($event, item)"
      >
        <span>
          <img
            style="margin-right: 4px; height: 16px"
            :src="item.icon"
          />
          <span v-if="item.name">{{ item.name }}</span>
        </span>
      </div>
    </div>

    <div
      v-if="selected && !row.readonly && !isModelDisabled"
      style="border-left: 1px solid #ddd; line-height: 14px"
      class="g-pd-4 g-flex-0"
    >
      <div>
        <img
          src="statics/icons/app/iconadd.png"
          class="g-pointer"
          @click="handleAdd"
        />
      </div>
      <div class="g-m-t-4">
        <img
          src="statics/icons/app/iconreduce.png"
          class="g-pointer"
          :class="{ _disable: valueData.length == 0 }"
          @click="handleRemove"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { PropertyRow, ModelValue } from "../../types";
import { ref, Ref, computed, watch, inject } from "vue";
import { propertyUtil } from "../../PropertyUtil";
import { modelService } from "@/modules/model/service/index";
import { propertyModelContextMenu } from "../propertyUtil";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

/**
 * 模型多选-树选择弹窗
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
}>();

const valueData = computed(() => {
  return (props.row.value || []) as ModelValue[];
});

const selectedModelId = ref("");

watch(
  () => props.selected,
  val => {
    if (val === false) {
      selectedModelId.value = "";
    }
  }
);

const handleAdd = async () => {
  const row = props.row;
  if (row.addModelItems) {
    await modelService.addModel(app.activeProject!.id, row.modelId, row.addModelItems[0].metaClass, []);
  }
  // if (result.code === 1000) {
  //       app.$bus.emit(BusEvent.REFRESH_POPERTY, row.modelId, row.key);
  //     }
};

function handleRemove() {
  if (!selectedModelId.value) {
    app.$notify({
      title: "提示",
      type: "error",
      message: "请选中元素再操作移除"
    });
    return;
  }
  propertyUtil.removePropertyAndRefresh(props.row, selectedModelId.value);
}

function handleClickItem(item: ModelValue) {
  selectedModelId.value = item.id;
}
</script>
<style lang="scss" scoped>
@import "@/assets/css/theme.scss";
.v-add-property {
  // height: 100%;
  ._disable {
    cursor: not-allowed;
    color: #c1c5cb;
    filter: grayscale(100);
  }
  ._selected {
    color: $theme-color;
  }
  ._list_scroll {
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }
  }
}
</style>
